package cn.ubest.mvvmcore.utils;

import android.app.Activity;

import java.util.Stack;

/**
 * Created by maoqi on 2020/3/17.
 */
public final class ActivityManager {
    private Stack<Activity> mActivities = new Stack<>();
    private static final ActivityManager mInstance = new ActivityManager();

    private ActivityManager() {

    }

    public static ActivityManager getInstance() {
        return mInstance;
    }

    public void addActivity(Activity activity) {
        mActivities.add(activity);
    }

    public void removeActivity(Activity activity) {
        KeyboardUtils.hideSoftInput(activity);
        activity.finish();
        mActivities.remove(activity);
    }

    public void removeActivity(Class<? extends Activity> tClass) {
        if (hasActivity(tClass)) {
            for (int size = mActivities.size(); size > 0; size--) {
                Activity activity = mActivities.peek();
                if (!tClass.getName().equals(activity.getClass().getName())) {
                    removeActivity(activity);
                }
            }
        }
    }

    public void removeAllActivity() {
        for (Activity activity : mActivities) {
            KeyboardUtils.hideSoftInput(activity);
            activity.finish();
        }
        mActivities.clear();
    }

    public Stack<Activity> getActivities() {
        return mActivities;
    }

    public <T extends Activity> boolean hasActivity(Class<T> tClass) {
        for (Activity activity : mActivities) {
            if (tClass.getName().equals(activity.getClass().getName())) {
                return !activity.isDestroyed() || !activity.isFinishing();
            }
        }
        return false;
    }

    /**
     * 获取当前Activity栈最顶的Activity
     * @return
     */
    public Activity getTopActivity() {
        return mActivities.peek();
    }

    public void closeTopActivity(Class<? extends Activity> tClass) {
        if (hasActivity(tClass)) {
            for (int size = mActivities.size(); size > 0; size--) {
                Activity activity = mActivities.peek();
                if (!tClass.getName().equals(activity.getClass().getName())) {
                    removeActivity(activity);
                }
            }
        }
    }

}
